import asyncio
import random
import time

# doc https://docs.python.org/zh-cn/3.9/library/asyncio-task.html#coroutine

async def main():
    print('hello')
    start = time.perf_counter()
    await asyncio.sleep(1)
    await asyncio.sleep(1)
    print(f'coast: {time.perf_counter() - start}')
    print('world')

async def main_create_task():
    start = time.perf_counter()
    async def task():
        await asyncio.sleep(1)
        print(random.randint(1, 10))
    
    task1 = asyncio.create_task(task())
    print('task1 --> ', task1)
    task2 = asyncio.create_task(task())

    await task1
    await task2

    print(f'coast: {time.perf_counter() - start}')


async def main_gather():
    async def factorial(name, number):
        f = 1
        for i in range(2, number + 1):
            print(f"Task {name}: Compute factorial({number}), currently i={i}...")
            await asyncio.sleep(1)
            f *= i
        print(f"Task {name} finished: factorial({number}) = {f}")
        return f
    L = await asyncio.gather(
        factorial("A", 2),
        factorial("B", 3),
        factorial("C", 4),
    )
    print(L)


async def main_gather2():
    async def sleep():
        await asyncio.sleep(1)
        return 'tiger'
    L = await asyncio.gather(
        sleep(),
        sleep(),
        sleep(),
    )
    print(L)
    

async def main_cancel_task():
    async def cancel_me():
        # await asyncio.sleep(3600)
        # print('asyncio.sleep(3600) ->', type(asyncio.sleep(3600)))
        return 43  # 如果发现return的不再需要进入asyncio循环 那么直接执行完毕
        return await asyncio.sleep(3600)  # 如果return的是Future 那么会等到执行完

    task = asyncio.create_task(cancel_me())
    await asyncio.sleep(1)
    task.cancel()  # 只有在task里面还有await代码的时候才会出现异常
    await task
    print('over')  # 如果exception, 那么会导致整个出现错误
    print(asyncio.get_event_loop_policy())
    asyncio.unix_events._UnixDefaultEventLoopPolicy


if __name__ == '__main__':
    asyncio.run(main_cancel_task())

